<script setup lang="tsx">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import useSchema from './hooks/useSchema'
import { useCrudSchemas, AllSchemas } from '@/hooks/web/useCrudSchemas'
import { getEditBackShowApi, getSalesEnumListApi } from '@/api/warehouse/merchandiseOffers'
import Gradient from '@/views/Warehouse/Inventory/components/Gradient/index.vue'

const { query } = useRoute()

const props = withDefaults(defineProps<{ index: number }>(), { index: 0 })

const gradientRef = ref<InstanceType<typeof Gradient> | null>(null)

const allSchemas = ref<AllSchemas>({
  formSchema: [] // 确保与接口匹配
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const submit = () => {
  return new Promise(async (resolve) => {
    const elForm = await getElFormExpose()
    await elForm?.validate(async (valid) => {
      if (valid) {
        const formData = await getFormData()
        for (const key in formData) {
          if (formData.hasOwnProperty(key) && key.includes('undefined')) {
            delete formData[key]
          }
        }
        const gradientData = await gradientRef.value?.gradientSubmit()
        resolve({ ...formData, ...{ gradientList: gradientData!.product_prices } })
      }
    })
  })
}

const fetchData = async () => {
  const saleResp = await getSalesEnumListApi({})
  const resp = await getEditBackShowApi(query.id as string)
  const { id, ...args } = query
  setValues({ ...resp.data, ...args })
  nextTick(() => {
    gradientRef.value?.queryDropDownBox(resp.data.product_prices || [], saleResp.data.wid)
  })
  // 在获取完所有数据后， 继续执行您希望在获取完数据后执行的代码
  const { crudSchemas } = useSchema({
    index: props.index,
    saleOptions: saleResp.data.is_sale
  })

  const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)
  allSchemas.value = {
    formSchema: newSchemas.formSchema || []
  }
}

fetchData()

defineExpose({
  submit
})
</script>

<template>
  <Form @register="formRegister" :schema="allSchemas.formSchema" />
  <Gradient ref="gradientRef" />
</template>

<style lang="less">
@import url('@/styles/global.less');
</style>
